package cn.edu.bupt.fluxdemo.controller;

import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.LocalTime;
import java.util.concurrent.TimeUnit;

@RestController
public class DemoController {
    private int count =1;

    @GetMapping("/flux/demo")
    public String fluxDemo() {
        Flux<String> flux = Flux.just("Hello", "world", "!");
        flux.subscribe(System.out::println);

        Mono<String> mono = Mono.just("Hello");
        mono.subscribe(System.out::println);

        Flux<Integer> numbers = Flux.range(1, 10);
        numbers.map(num -> num * 2)
                .filter(num -> num % 3 == 0)
                .subscribe(System.out::println);

        return "flux-demo-done";
    }



    @GetMapping("/flux/delay-echo")
    public Mono<String> handle() {
        System.out.println(Thread.currentThread().getName()+" Start");
        Mono<String> stringMono = Mono.just ("delay-echo")
                .delayElement (Duration.ofMillis (5000));
        System.out.println(Thread.currentThread().getName()+" End");
        return stringMono;
    }


    @GetMapping("/flux/sse")
    public Flux<ServerSentEvent<String>> randomNumbers() {
        return Flux.range(0,20).delayElements(Duration.ofMillis (1000))
                .map(seq ->ServerSentEvent.<String>builder()
                        .id(Long.toString(seq))
                        .data(LocalTime.now().toString())
                        .build());

    }

}
